﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using OplugAbpProject.Transaction.Dto;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace OplugAbpProject.Transaction
{
    public class AttachmentAppService: AsyncCrudAppService<Attachments, AttachmentDto, long, PagedResultRequestDto, CreateAttachmentDto, UpdateAttachmentDto>
    {
        private readonly IObjectMapper _objectMapper;
        private readonly IHostingEnvironment _hostingEnvironment;
        public AttachmentAppService(IRepository<Attachments, long> repository, IObjectMapper objectMapper) : base(repository)
        {
            _objectMapper = objectMapper;
        }

        public async Task<string> UploadFiles(IFormFileCollection files)
        {
            //string webRootPath = _hostingEnvironment.WebRootPath;
            //string contentRootPath = _hostingEnvironment.ContentRootPath;
            //string imageName = String.Empty;
            StringBuilder filenames = new StringBuilder();
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    string fileExt = Path.GetExtension(formFile.FileName);
                    long fileSize = formFile.Length;
                    string newName = Guid.NewGuid().ToString() + fileExt;                   

                    Stream stream = formFile.OpenReadStream();
                    byte[] bytes = new byte[stream.Length];
                    await stream.ReadAsync(bytes, 0, bytes.Length);                    
                    Repository.Insert(new Attachments()
                    {
                        FileName = newName,
                        FileExtension = fileExt,
                        FileSize = fileSize,
                        FileData = bytes
                    });
                    stream.Close();

                    //var fileDire = webRootPath + string.Format("/Attachments/Upload/", "");
                    //if (!Directory.Exists(fileDire))
                    //{
                    //    Directory.CreateDirectory(fileDire);
                    //}
                    //var filePath = fileDire + newName;
                    //using (var stream = new FileStream(filePath, FileMode.Create))
                    //{                        
                    //    await formFile.CopyToAsync(stream);
                    //}
                    filenames.Append(newName + ",");
                    
                }
            }
            return filenames.ToString();
        }
    }
}
